import xlrd, os
from trade import models
import django.db.utils

def updateDomain(file_path):
  """
  处理excel表格上传域名信息
  :param file_path: excel文件存放的路径+名称
  :return: 返回一个处理后的状态
  """
  status = '0'
  if os.path.isfile(file_path):
    workbook = xlrd.open_workbook(file_path)
    sheets = workbook.sheet_by_index(0)
    nrows = sheets.nrows
    ncols = sheets.ncols
    title = sheets.row_values(0)
    for i in range(1,nrows):
      domain_info_dic = {}
      doamin_name = sheets.row_values(i)[0]
      transaction_type = 2
      for k in range(1,ncols):
        key = title[k]
        value = sheets.row_values(i)[k]
        if title[k] == '域名类型':
          domain_type = sheets.row_values(i)[k]
        if title[k] == '交易类型':
          if sheets.row_values(i)[k] == '一口价':
            value = str(1)
            transaction_type = int(value)
          elif sheets.row_values(i)[k] == '竞价':
            value = str(0)
            transaction_type = int(value)
          elif type(sheets.row_values(i)[k]) == float or \
                  type(type(sheets.row_values(i)[k])) == int :
            value = str(int(value))
            transaction_type = int(value)
          else:
            value = str(2)
        domain_info_dic[key] = value
      db_dict = {
        'domain_name': doamin_name,
        'domain_info': domain_info_dic,
        'domain_type': domain_type,
        'transaction_type': transaction_type,
        'status': 0,
      }
      try:
        domain_db_info = models.DomainList.objects.filter(domain_name=doamin_name).first()
        if domain_db_info:
          if transaction_type != domain_db_info.transaction_type:
            models.DomainList.objects.filter(domain_name=doamin_name).update(transaction_type=transaction_type)
          if eval(domain_db_info.domain_info) != domain_info_dic:
            models.DomainList.objects.filter(domain_name=doamin_name).update(domain_info=domain_info_dic)
          if domain_type != domain_db_info.domain_type:
            models.DomainList.objects.filter(domain_name=doamin_name).update(domain_type=domain_type)
        else:
          models.DomainList.objects.create(**db_dict)
      except (django.db.utils.DatabaseError):
        return '0'
    return '1'
  return status
